# 提取公共参数
war_relative_path=sdk-server/target/
war_name=ROOT
project_name="YIHAO-SDK-SERVER"
deploy_tomcat_path=/data/www/jenkins.yihao.tt.cn
dingurl="https://oapi.dingtalk.com/robot/send?access_token=0040312ab3892b5ca1c14d2cd31f7483df7660e1e88ffdd29f1a8fa10a1c4135"
nginx_hosts=(172.31.65.68)
ngx_upstream_file="/etc/nginx/servers/useless.platform.upstream"


# 部署脚本开始, 下面可提取出公参丢到服务器上
echo "当前ip：${DEPLOY_HOST}"
echo "包md5值：$(md5sum ${war_relative_path}${war_name}.war)"
echo "编译分支：${GIT_BRANCH}"

release_war=$(echo "${GIT_BRANCH}" | cut -d '/' -f 2)

cp ${war_relative_path}${war_name}.war ${war_relative_path}${release_war}.war

PURE_DEPLOY_MACHINE=`echo "${DEPLOY_HOST}" | sed 's/\[[a-zA-Z0-9\-]*\] //g'`

DOWN_WAITING_SEC=15

OLD_IFS="$IFS"
IFS=","
arr=($DEPLOY_HOST)

IFS="$OLD_IFS"

curl -i -X POST -H "Content-Type: application/json;charset=utf-8" -i --data '{
      "msgtype": "actionCard",
      "actionCard": {
          "title": "部署告警",
          "text": "### 服务部署 \n ## ['${project_name}'] \n- 部署分支: '${GIT_BRANCH}'\n- 发布人: '${BUILD_USER}'\n- 原因：'${REASON}'\n- 目标机器：'${PURE_DEPLOY_MACHINE}'\n- 自动上负载：'${AUTO_UP}'\n- 仅分发包：'${ONLY_CP_WAR}'",
          "hideAvatar": "0",
          "btnOrientation": "0"
      },
      "at": {
          "atMobiles": [
            "18505656155"
          ],
      "isAtAll": false
      }
}' ${dingurl}


#遍历数组
for target_host in ${arr[@]}; do

  
  if [[ ${target_host} =~ "]" ]]; then
  
    echo ""
   
  else

    # 创建备份目录
    ssh -o StrictHostKeyChecking=no -p 59522 root@${target_host} "mkdir -p /data/deployment/backup/${war_name}"
    ssh -o StrictHostKeyChecking=no -p 59522 root@${target_host} "mkdir -p /data/deployment/release/${war_name}"

    # 备份旧包
    curr_bak_date=$(date +%Y%m%d_%H%M%S)
    ssh -o StrictHostKeyChecking=no -p 59522 root@${target_host} "if [ -f /data/deployment/release/${war_name}/${release_war}.war ]; then mv /data/deployment/release/${war_name}/${release_war}.war /data/deployment/backup/${war_name}/${release_war}_${curr_bak_date}.war; fi"

    if [ "${ONLY_CP_WAR}" == "false" ]; then
      # 负载下线
      for nginx_host in ${nginx_hosts[@]}; do
				ssh -o StrictHostKeyChecking=no -p 59522 root@${nginx_host} "/data/deployment/bin/down_nginx.sh ${target_host} ${ngx_upstream_file}"
			done

      # 告警下线
      curl -i -X POST -H "Content-Type: application/json;charset=utf-8" -i --data '{
          "msgtype": "actionCard",
          "actionCard": {
              "title": "部署告警",
              "text": "### 部署机器: '${target_host}' 服务下线 \n ## ['${project_name}'] \n- 部署分支: '${GIT_BRANCH}'\n- 发布人: '${BUILD_USER}'\n- INFO: 等候'${DOWN_WAITING_SEC}'s流量净空重启",
              "hideAvatar": "0",
              "btnOrientation": "0"
          },
          "at": {
            "atMobiles": [
                "18505656155"
              ],
          "isAtAll": false
          }
      }' ${dingurl}

      # 等待下线成功，没有新的请求访问
      ssh -o StrictHostKeyChecking=no -p 59522 root@${target_host} "/data/deployment/bin/lb_assistant.sh ${DOWN_WAITING_SEC} ${deploy_tomcat_path}"
    else
      echo "==================================== ONLY COPY WAR ===================================="
    fi

    # 推送新包
    scp -o StrictHostKeyChecking=no -P 59522 ${war_relative_path}${release_war}.war root@${target_host}:/data/deployment/release/${war_name}/

    if [ "${ONLY_CP_WAR}" == "false" ]; then
      curl -i -X POST -H "Content-Type: application/json;charset=utf-8" -i --data '{
          "msgtype": "actionCard",
          "actionCard": {
              "title": "部署告警",
              "text": "### '${target_host}' 服务重启 \n ## ['${project_name}'] \n- 部署分支: '${GIT_BRANCH}'\n- 部署人: '${BUILD_USER}'",
              "hideAvatar": "0",
              "btnOrientation": "0"
          },
          "at": {
              "atMobiles": [
                "18505656155"
              ],
          "isAtAll": false
          }
      }' ${dingurl}

      # 停tomcat
      ssh -o StrictHostKeyChecking=no -p 59522 root@${target_host} "/data/deployment/bin/kill_web.sh ${deploy_tomcat_path}"

      sleep 5


      # 复制release包到目标tomcat下
      ssh -o StrictHostKeyChecking=no -p 59522 root@${target_host} "cp /data/deployment/release/${war_name}/${release_war}.war ${deploy_tomcat_path}/webapps/${war_name}.war"


      # 重启tomcat，并查看最后的日志输出是否包含启动成功日志
      ssh -o StrictHostKeyChecking=no -p 59522 root@${target_host} "source /etc/profile;${deploy_tomcat_path}/bin/startup.sh"
      
      sleep 5
      
      # 检查服务是否正常启动
      ssh -o StrictHostKeyChecking=no -p 59522 root@${target_host} "/data/deployment/bin/detect_tomcat_available.sh ${DOWN_WAITING_SEC} ${deploy_tomcat_path}"

      sleep 5

    fi

    if [ "${AUTO_UP}" == "true" ]; then

      if [ "${ONLY_CP_WAR}" == "false" ]; then
        # 负载上线
        for nginx_host in ${nginx_hosts[@]}; do
					ssh -o StrictHostKeyChecking=no -p 59522 root@${nginx_host} "/data/deployment/bin/up_nginx.sh ${target_host} ${ngx_upstream_file}"
				done
				
        curl -i -X POST -H "Content-Type: application/json;charset=utf-8" -i --data '{
          "msgtype": "actionCard",
          "actionCard": {
              "title": "部署告警",
              "text": "### 部署机器: '${target_host}' 服务上线 \n ## ['${project_name}'] \n- 部署分支: '${GIT_BRANCH}'\n- 部署人: '${BUILD_USER}'",
              "hideAvatar": "0",
              "btnOrientation": "0"
          },
          "at": {
              "atMobiles": [
                "18505656155"
              ],
          "isAtAll": false
          }
      }' ${dingurl}

      else
        echo "auto up but only copy war mode."

        echo "==================================== LOAD BALANCE【OFFLINE】 ===================================="
      fi
    else

      echo "==================================== LOAD BALANCE【OFFLINE】 ===================================="

    fi
  
  fi

done